﻿using Common;
using Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Web.Areas.Mobile.Lib;
using Web.Lib;
using Web.Libs;

namespace Web.Areas.Mobile.Controllers
{
    public class UserController : BaseController
    {
        public ActionResult LogOut()
        {
            MobileAccount.LogOut();
            return SuccessMsg("注销成功！");
        }
        /// <summary>
        /// 服务号授权
        /// </summary>
        public ActionResult Auth(string openid, string redirectUrl)
        {
            var queryParams = GenerateQuerString();

            if (string.IsNullOrWhiteSpace(redirectUrl))
            {
                redirectUrl = "/mobile/survey/mark";
            }
            if (MobileAccount.ID > 0)
            {
                return Redirect(GenerateUrl(redirectUrl.Replace("_", "/"), queryParams));
            }

            if (!string.IsNullOrWhiteSpace(openid))
            {
                //保存至浏览器cookie
                var r = new MobileAccount().LogOn(openid);
                if (r)
                {
                    if (MobileAccount.GetUser.type == (int)UserType.None)
                    {
                        return Redirect("/mobile/user/register");
                    }
                    else
                    {
                        return Redirect(GenerateUrl(redirectUrl.Replace("_", "/"), queryParams));
                    }
                }
                else
                {
                    return Redirect("/mobile/survey/notopen?msg=无法获取您的用户信息！");
                }
            }

            string appid, appsecret;
            new Admin.Lib.Site().GetAppConfig(out appid, out appsecret);

            var redirectUri = eDoctor.SDK.WeChat.WebPage.Call.authorize(appid, Common.UrlHelper.HostUrl + "/mobile/user/oauth?" + queryParams, "QAZEDCTGB");

            if (!string.IsNullOrWhiteSpace(redirectUri))
            {
                return Redirect(redirectUri);
            }
            else
            {
                return Redirect("/mobile/survey/notopen?msg=无法获取您的用户信息！");
            }
        }
        /// <summary>
        /// 授权回调
        /// </summary>
        /// <returns></returns>
        public ActionResult OAuth(string code, string state, string redirectUrl)
        {
            wx_usersLogic ul = new wx_usersLogic();
            string appid, appsecret;
            if (new Admin.Lib.Site().GetAppConfig(out appid, out appsecret))
            {
                //通过code换取网页授权access_token
                var webtoken = eDoctor.SDK.WeChat.WebPage.Call.access_token(appid, appsecret, code);
                //判断授权是否成功
                if (webtoken == null || string.IsNullOrEmpty(webtoken.openid))
                {
                    return Redirect("/mobile/survey/notopen?msg=无法获取您的用户信息！");
                }
                var access_token = new Admin.Lib.Site().GetAccessToken();
                //判断是否存在用户
                var dbWuser = ul.Getwx_users(new wx_users { openid = webtoken.openid });
                if (dbWuser == null)
                {
                    wx_users newUser = new wx_users { createdate = DateTime.Now, openid = webtoken.openid };
                    var u = new eDoctor.SDK.WeChat.Call(access_token).GetUserInfo(webtoken.openid, true);
                    if (u.errcode != 0)
                    {
                        return Redirect("/mobile/survey/notopen?msg=无法获取您的用户信息！");
                    }
                    else
                    {
                        newUser.nickname = u.nickname;
                        newUser.headimgurl = u.headimgurl;
                    }
                    var result = ul.Add(newUser);
                    if (!result)
                    {
                        return Redirect("/mobile/survey/notopen?msg=无法获取您的用户信息！");
                    }
                    else
                    {
                        //登录
                        new MobileAccount().LogOn(webtoken.openid);
                        return Redirect("/mobile/survey/mark");
                    }
                }
                else
                {
                    //登录
                    new MobileAccount().LogOn(webtoken.openid);
                    if (MobileAccount.GetUser.type == (int)UserType.None)
                    {
                        return Redirect("/mobile/user/register");
                    }
                    else
                    {
                        if (string.IsNullOrWhiteSpace(redirectUrl))
                        {
                            redirectUrl = "/mobile/survey/mark";
                        }
                        //自带参数
                        var querystring = string.Empty;
                        foreach (string key in Request.QueryString.Keys)
                        {
                            if (key != "code" && key != "state" && key.ToLower() != "redirecturl")
                            {
                                querystring += "&" + key + "=" + Request.QueryString[key];
                            }
                        }
                        return Redirect(redirectUrl.Replace("_", "/") + (redirectUrl.IndexOf("?") < 0 ? "?" : "&") + querystring);
                    }
                }
            }
            else
            {
                return Redirect("/mobile/survey/notopen?msg=无法获取您的用户信息！");
            }
        }

        public ActionResult Register()
        {
            if (MobileAccount.GetUser.type != (int)UserType.None)
            {
                return Redirect("/mobile/survey/mark");
            }
            return View();
        }

        [HttpPost]
        public ActionResult Register(string mobile, string code)
        {
            try
            {
                wx_usersLogic ul = new wx_usersLogic();
                expertLogic el = new expertLogic();

                MobileAccount account = new MobileAccount();
                var dbUser = ul.Getwx_users(MobileAccount.ID);
                if (dbUser == null || MobileAccount.ID == 0)
                {
                    MobileAccount.LogOut();
                    return ErrorMsg("登录状态已失效，请点击菜单重新认证！");
                }
                var sms = System.Web.HttpContext.Current.Session[mobile];
                if (code != System.Configuration.ConfigurationManager.AppSettings["CommonSMS"])
                {
                    if (sms == null)
                    {
                        return ErrorMsg("验证码已过期，请重新发送");
                    }
                    if (code != sms.ToString())
                    {
                        return ErrorMsg("验证码错误！");
                    }
                }
                var mobileUsers = ul.Getwx_userss(new wx_users { mobile = mobile }, string.Format(" and id!={0}", MobileAccount.ID));
                if (mobileUsers.Count > 0)
                {
                    return ErrorMsg("此手机号码已被使用！");
                }
                var dbExpert = el.Getexpert(new expert { mobile = mobile });
                if (dbExpert != null)
                {
                    if (dbExpert.userid == MobileAccount.ID)
                    {
                        return ErrorMsg("您已经认证过！");
                    }
                    dbExpert.userid = MobileAccount.ID;
                    dbExpert.modifydate = DateTime.Now;
                    dbExpert.modifyuserid = MobileAccount.ID;
                    var r = el.Update(dbExpert);
                    if (r)
                    {

                        dbUser.mobile = mobile;
                        dbUser.type = (int)UserType.Expert;
                        ul.Update(dbUser);
                        account.LogOn(dbUser.openid);
                        return SuccessMsg("认证成功！您的身份是" + dbUser.TypeStr);
                    }
                    else
                    {
                        return ErrorMsg("认证失败！");
                    }
                }
                else
                {
                    dbUser.mobile = mobile;
                    dbUser.type = (int)UserType.Public;
                    ul.Update(dbUser);
                    account.LogOn(dbUser.openid);
                    return SuccessMsg("认证成功！您的身份是" + dbUser.TypeStr);
                }
            }
            catch (Exception e)
            {
                return ErrorMsg(e.Message);
            }
        }

        #region 发送验证码
        [HttpPost]
        public ActionResult GetAuthCode(string mobile)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(mobile))
                {
                    return ErrorMsg("请填写手机号码！");
                }
                else
                {
                    string sms = Character.RandomString("num", 6);
                    var r = AliyunSmsHelper.SendCode(mobile, sms);
                    if (!r)
                    {
                        return ErrorMsg("验证码发送失败，请稍后再试！");
                    }
                    System.Web.HttpContext.Current.Session[mobile] = sms;

                    HttpCookie cookies = new HttpCookie("Expires");
                    cookies["Timer"] = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                    cookies.Expires = DateTime.Now.AddMinutes(15);
                    Response.Cookies.Add(cookies);

                    return SuccessMsg("验证码已通过短信发送到您的手机，15分钟内有效，请注意查收！");
                }
            }
            catch (Exception e)
            {
                return ErrorMsg(e.Message);
            }
        }
        #endregion


    }
}
